package main

import (
	"fmt"
	"net/http"
	"time"

	business "example.com/m/com.business"
	common "example.com/m/com.common"
	qfcfg "example.com/m/com.qfcfg"
	qfcrypt "example.com/m/com.qfcrypt"
	qflog "example.com/m/com.qflog"
	qfmysql "example.com/m/com.qfmysql"
	qfredis "example.com/m/com.qfredis"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)


// middleWare def
func middleWare(c *gin.Context) {
	start := time.Now()
	business.Controller{}.CheckTraceID(c)
	traceID := c.Request.Header.Get(common.TraceID)
	c.Next()
	// 统计时间
	since := time.Since(start)
	qflog.Sugare.Infof("TraceID=%s|cost: %v", traceID, since)
}

func newRouter() *gin.Engine {
	r := gin.New()
	// gin 日志也写到文件
	gin.DefaultWriter = qflog.LumberJackLogger
	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	// 注册中间件
	r.Use(middleWare)

	api := r.Group("/")
	{
		api.GET("/notice", business.Controller{}.NoticeHandler)
		api.GET("/redis", business.Controller{}.RedisHandler)
		api.GET("/cava3/outputs/log/:dirname/:filename", business.Controller{}.DownloadHandler)
		api.GET("/cava3/upload/:filename", business.Controller{}.DownloadHandler)
		api.GET("/lock", business.Controller{}.LockHandler)

		api.POST("/authorization", business.Controller{}.AuthHandler)
		api.POST("/register", business.Controller{}.RegistHandler)
		api.POST("/encrypt", business.Controller{}.EncryptHandler)
		api.POST("/decrypt", business.Controller{}.DecryptHandler)
		api.POST("/cava3/upload", business.Controller{}.UploadHandler)
	}

	return r
}

func httpServer() {
	address := fmt.Sprintf("%s:%d", qfcfg.ServerConfig.Server.IP, qfcfg.ServerConfig.Server.Port)

	router := newRouter()
	s := &http.Server{
		Addr:           address,
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}

func initCrypt() {
	// currentVersionFlag := "=DhaV="
	currentVersionFlag := "QFTECH"
	key := "lmN4dtPyeC5r29DYBLl0P0OoA4Afy/2UnCg0zd+hHhg="

	var oldKeys map[string][]byte
	oldKeys = make(map[string][]byte)
	zeroKeytr := "q_1dY=Khec2nMNxV"
	oldKeys[qfcrypt.ZeroVersionFlag] = []byte(zeroKeytr)

	qfcrypt.Init(currentVersionFlag, []byte(key), oldKeys)
}

func main() {
	qflog.InitLog()
	initCrypt()
	qfcfg.InitConfig()
	_ = qfredis.InitRedisPool()
	_ = qfmysql.InitMysqlDB()
	go httpServer()
	select {}
}
